/* ******************************************************************************
 * FileHandler.java
 * 创建日期:2017年12月28日
 * Copyright 2017 kingter company, Inc. All rights reserved.
 * xxxx PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *******************************************************************************/
package com.ball.tools.handlers;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;
import org.nanohttpd.router.RouterNanoHTTPD;
import org.nanohttpd.router.RouterNanoHTTPD.Error404UriHandler;
import org.nanohttpd.router.RouterNanoHTTPD.StaticPageHandler;
import org.nanohttpd.router.RouterNanoHTTPD.UriResource;

/**
 * <p>标题: FileHandler</p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: xxxx</p>
 * <p>描述: </p>
 * 
 * @version 1.0
 * @author xieyicai
 */
public class FileHandler extends StaticPageHandler {
	/**  */
	private Error404UriHandler handler404 = new Error404UriHandler();
	/**
	 * 
	 */
	public FileHandler() throws IOException {
	}

	public Response get(UriResource uriResource, Map<String, String> urlParams, IHTTPSession session) {
		String baseUri = uriResource.getUri();
		String realUri = RouterNanoHTTPD.normalizeUri(session.getUri());
		int min = Math.min(baseUri.length(), realUri.length());
		for (int index = 0; index < min; index++) {
			if (baseUri.charAt(index) != realUri.charAt(index)) {
				realUri = RouterNanoHTTPD.normalizeUri(realUri.substring(index));
				break;
			}
		}
		File homeDir = uriResource.initParameter(0, File.class);
		File fileOrdirectory = new File(homeDir, realUri);
		if(fileOrdirectory.toString().startsWith(homeDir.toString())){
			if (fileOrdirectory.isDirectory()) {
				fileOrdirectory = new File(fileOrdirectory, "index.html");
				if (!fileOrdirectory.exists()) {
					fileOrdirectory = new File(fileOrdirectory.getParentFile(), "index.htm");
				}
			}
			if (!fileOrdirectory.exists() || !fileOrdirectory.isFile()) {
				return handler404.get(uriResource, urlParams, session);
			} else {
				try {
					return Response.newChunkedResponse(getStatus(), NanoHTTPD.getMimeTypeForFile(fileOrdirectory.getName()), fileToInputStream(fileOrdirectory));
				} catch (IOException ioe) {
					return Response.newFixedLengthResponse(Status.REQUEST_TIMEOUT, "text/plain", (String) null);
				}
			}
		}else{
			return handler404.get(uriResource, urlParams, session);
		}
	}
}
